package top.sdwu_top.kbase.service.impl;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.sdwu_top.kbase.entity.elastic.EsFile;
import top.sdwu_top.kbase.mapper.elastic.KbaseFileEsMapper;
import top.sdwu_top.kbase.service.IEsFileService;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EsFileServiceImpl implements IEsFileService {

    @Autowired
    KbaseFileEsMapper fileEsMapper;


    @Override
    public List<String> listByKeyword(String keyword, List<String> inIds) {
        Iterator<EsFile> fileIterator = fileEsMapper.search(
                QueryBuilders.multiMatchQuery(keyword,
                        "fileName", "content")).iterator();
        List<EsFile> fileList = Lists.newArrayList();
        while (fileIterator.hasNext()) {
            fileList.add(fileIterator.next());
        }
        return fileList.parallelStream().map(EsFile::getId).collect(Collectors.toList());
    }

    @Override
    public List<String> listByKeyword(String keyword) {
        QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword,
                "fileName", "content", "tags");
        log.info("{}", queryBuilder);
        Iterator<EsFile> fileIterator = fileEsMapper.search(queryBuilder).iterator();
        List<EsFile> fileList = Lists.newArrayList();
        while (fileIterator.hasNext()) {
            fileList.add(fileIterator.next());
        }
        return fileList.parallelStream().map(EsFile::getId).collect(Collectors.toList());
    }

    public EsFile save(EsFile esFile) {
        return fileEsMapper.save(esFile);
    }


    @Override
    public List<EsFile> list() {
        Iterator<EsFile> fileIterator = fileEsMapper.search(QueryBuilders.matchAllQuery()).iterator();
        List<EsFile> esFiles = Lists.newArrayList();
        while (fileIterator.hasNext()) {
            esFiles.add(fileIterator.next());
        }
        return esFiles;
    }

}
